#include "TextEditor.h"
#include <QDateTime>
#include <QTextCodec>

TextEditor::TextEditor()
{
	_dec = QTextCodec::codecForName("EUC-KR");
	_enc = QTextCodec::codecForName("EUC-KR");
}

QString TextEditor::MessageTextProcessing(bool isTx, QString rawData, QString from, QString with, QString fileName)
{
	QString msg;
	msg = from +
		  '\n' +
		  QDateTime::currentDateTime().toString("(MM/dd(ddd)APhh:mm)") +
		  '\n' +
		  "wwwwwwwwwwith:" + with +
		  '\n';
	if (isTx)
		  msg += "---------------------------\n";
	if (fileName != "")
	{
		msg += QString::fromUtf8("[첨부]");
		msg += (fileName + '\n');
	}

	msg += rawData;
//	return _enc->toUnicode(msg.toAscii(), msg.size());
	return msg;
}

QString TextEditor::ReceiveMessageTextProcessing(QByteArray stream)
{
	QString message = "";
	char *rawData = new char[stream.length() + 1];
	if (rawData != NULL)
	{
		memcpy(rawData, stream.data(), stream.length());
		rawData[stream.length()] = '\0';

		char *from = rawData;
		char *dateTime = strchr(rawData, '\n');
		if (dateTime != NULL)
		{
			//*dateTime++ = ')';
			*dateTime++ = '\0';
			char *to = strchr(dateTime, '\n');
			if (to != NULL)
			{
				*to++ = ')';
				*to++ = '\0';
				to = strchr(to, ':');
				if (to != NULL)
				{
					to++;
					char *msg = strchr(to, '\n');
					if (msg != NULL)
					{
						*msg++ = '\0';
						message = QString("%1\n%2\n%3").
								  arg(_dec->toUnicode(from, strlen(from))).
								  arg(_dec->toUnicode(dateTime, strlen(dateTime))).
								  arg(_dec->toUnicode(msg, strlen(msg)));
					}
				}
			}
		}
		delete [] rawData;
	}
	return message;
}


QString TextEditor::LogReadTextProcessing(QByteArray rawData)
{
	QString rawStr(rawData);
	rawStr.remove("==============================================================");
	int idx = rawStr.indexOf('\n');
	rawStr.remove(0, idx +1 );
	return QString::fromUtf8(rawStr.toAscii().data(), rawStr.size());
}

QString TextEditor::LogWriteTextProcessing(QString rawData, bool isTx)
{
	if (isTx)
		rawData.push_front("#Send\n");
	else
		rawData.push_front("#Received\n");
	rawData.push_front("==============================================================\n");
	rawData.push_back('\n');
	return QString(rawData.toUtf8());
}

QString TextEditor::GetCurrentTimeforLog()
{
	return QDateTime::currentDateTime().toString("yyyyMMdd.txt");
}

static TextEditor g_textEditor;
TextEditor *GetTextEditor()
{
	return &g_textEditor;
}
